/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.PooledConnection;

/**
 *
 * @author moustafa
 */
public class Login extends HttpServlet {

    private MysqlConnectionPoolDataSource dataSource;
    @Override
    public void init() throws ServletException {
        super.init();
        dataSource = new MysqlConnectionPoolDataSource();
        dataSource.setUser("badawise");
        dataSource.setPassword("mysqlpass");
        dataSource.setServerName("localhost");
        dataSource.setPort(3306);
        dataSource.setDatabaseName("infosys");
        InitialContext context;
        try {
            context = new InitialContext();
            context.bind("jdbc/MySQLDB", dataSource);
        } catch (NamingException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        Cookie cookies[] = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if(cookies[i].getName().equals("username") == true){
                HttpSession session = request.getSession(true);
                session.setAttribute("username", cookies[i].getValue());
                getServletContext().getRequestDispatcher("/welcome.jsp").forward(request, response);
                return;
            }
        }
        getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PooledConnection pConn =null;
        Connection conn = null;
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try
        {
            //String dbUsername = "badawise";
            //String dbPassword = "mysqlpass";
            //String url = "jdbc:mysql://localhost/infosys";
            pConn = dataSource.getPooledConnection();
            conn = pConn.getConnection();
            //Class.forName ("com.mysql.jdbc.Driver").newInstance ();
            //conn = DriverManager.getConnection (url, dbUsername, dbPassword);
            Statement statement = conn.createStatement();
            statement.executeQuery ("SELECT id FROM users WHERE username='"+ username + "' AND password='"+password+"'");
            ResultSet rs = statement.getResultSet ();
            HttpSession session = request.getSession(true);
            if(rs.next()){
                Cookie cookie = new Cookie("username", username);
                cookie.setMaxAge(30);
                response.addCookie(cookie);
                session.setAttribute("username", username);
                getServletContext().getRequestDispatcher("/welcome.jsp").forward(request, response);
                //response.sendRedirect("welcome.jsp");
            }else{
                session.setAttribute("error", "User not found!");
                getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
            }
            rs.close ();
            statement.close ();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            //out.println ("Cannot connect to database server");
        }
        finally
        {
           if (conn != null)
           {
               try
               {
                   conn.close ();
               }
               catch (Exception e) { /* ignore close errors */ }
           }
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
